package com.myStruts.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.myStruts.bean.XmlBean;

public class StrutsConfig {

	public StrutsConfig() {
	}

	public static Map<String, XmlBean> initXml(String xmlPath) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(xmlPath);
		Element root = document.getRootElement();

		Map<String, XmlBean> xmlMap = new HashMap<String, XmlBean>();
		Element mapping = root.getChild("action-mapping");
		List<Element> mappingList = mapping.getChildren();

		for (Element action : mappingList) {
			XmlBean xmlBean = new XmlBean();

			String beanId = action.getAttributeValue("id");
			Element beanElement = root.getChild("formBeans");
			List<Element> beanList = beanElement.getChildren();
			for (Element bean : beanList) {
				String beanName = bean.getAttributeValue("name");
				if (beanName.equals(beanId)) {
					String beanClass = bean.getAttributeValue("class");
					xmlBean.setBeanName(beanName);
					xmlBean.setBeanClass(beanClass);
					break;
				}
			}

			String path = action.getAttributeValue("path");
			String aClass = action.getAttributeValue("class");
			xmlBean.setPath(path);
			xmlBean.setActionClass(aClass);

			Map<String, String> map = new HashMap<String, String>();
			List<Element> forwardList = action.getChildren();
			for (Element forward : forwardList) {
				String key = forward.getAttributeValue("name");
				String value = forward.getAttributeValue("value");
				map.put(key, value);
			}
			xmlBean.setActionForward(map);
			xmlMap.put(path, xmlBean);
		}
		return xmlMap;
	}

}
